package amf
{
	import data.Man;
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import data.Person;
	
	/**
	 * ...
	 * @author gp
	 */
	public class AmfMain
	{
		
		public function AmfMain()
		{
			//this.save();
			this.read();
		}
		
		private function save():void
		{
			//必须在写入前注册
			registerClassAlias( "data.Man", Man );
			registerClassAlias("data.Person", Person);
			
			var bytes:ByteArray = new ByteArray();
			bytes.endian = Endian.LITTLE_ENDIAN;
			
			var person:Person = new Person();
			person.firstName = "潘俊ab";
			person.lastName = "Alan";
			person.age = 37.66;
			bytes.writeObject(person);
			
			//			
			//						bytes.writeInt(111);
			//						var idxOld:uint = bytes.position;
			//						bytes.position += 2;
			////						bytes.writeUTF("测试1");
			//						bytes.writeUTFBytes("测试1");
			//						var idxNew:uint = bytes.position;
			//						bytes.position = idxOld;
			//						bytes.writeShort(7);
			//						bytes.position = idxNew;
			
			var file:FileReference = new FileReference ();
			file.save(bytes,"data.dat");//第二个参数为默认文件名,不能设路径
			
			//bytes.position = 0;
			//var person1:Person = bytes.readObject();
			//trace(person1 is Person); //true
			//trace(person1.firstName); //Lee
		
			//			trace(bytes.readInt());
			//			trace(bytes.readShort());
			//			trace(bytes.readUTFBytes(6));
		}
		
		private function read():void
		{
			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE, loaded);
			loader.load(new URLRequest("res/data.dat"));
		}
		
		private function loaded(evt:Event):void
		{
			var loader:URLLoader = evt.target as URLLoader;
			var bytes:ByteArray = loader.data as ByteArray;
			bytes.endian = Endian.LITTLE_ENDIAN;
			trace("loaded:...", bytes.length);
			
			//如果之前没注册，读取前必须注册
			registerClassAlias( "data.Man", Man );
			registerClassAlias("data.Person", Person);
			
			bytes.position = 0;
			
			var person:Person = bytes.readObject() as Person;
			person.show();
			
			//var amf3:AMF3 = new AMF3();
			////trace(amf3.readData(bytes));
			//var person:Person = amf3.readData(bytes) as Person;//转换失败
			//person.show();
			
			trace("is Person: ", person is Person); //true
			trace(person.firstName); //Lee
			trace(person.lastName);
			trace(person.age);
		//
			//			trace(bytes.readInt());
			//			//						trace(bytes.readUTF());
			//			var len:uint = bytes.readUnsignedShort();
			//			trace(len);
			//			trace(bytes.readUTFBytes(len));
		}
	}

}